#define LOG_TAG "resource"

#include "dataflow.h"
#include "cJSON_ext.h"

const char * target_di = "aaa";
const char * target_ri = "bbb";

void data_global_handler(restful_request_t * request, REQ_ENV_HANDLE req_env)
{
    static int cnt = 0;
    cnt ++;
    WALOG("data_global_handler ENTER. (%d)", cnt);
    wa_data_notify_t * notify = wa_monitor_parse_notification_A(request);
    if(notify == NULL)
    {
        WARNING2("Invalid data notify. query: %s", request->query?request->query:"null");
        return;
    }

    if(notify->require_response)
    {
        WARNING("notify require process. It is abnormal as we didn't set it!");
    }

    // Just show the incoming tag is the one we created the monitor
    assert(strcmp(notify->tag, "tag1") == 0);

    if(strcmp(notify->device_id, target_di)==0 && 
        strcmp(notify->resource_id, target_ri)==0)
    {
        WALOG("dat:%s", request->payload);
    }

    wa_monitor_set_decision(req_env, cnt%2?WA_Process_Continue:WA_Process_Drop);
}


void data_mon1_handler( restful_request_t * request, REQ_ENV_HANDLE req_env)
{
    wa_data_notify_t * notify = wa_monitor_parse_notification_A(request);
    if(notify == NULL)
    {
        WARNING2("Invalid data notify. query: %s", request->query?request->query:"null");
        return;
    }

    // this should not happen. Just to show the API usages.
    if(!notify->require_response)
    {
        WARNING("notify doesn't require process. It is abnormal as we set it!");
        wa_monitor_set_decision(req_env, WA_Process_No_Response);
        return;
    }
    double value;
    if(request->payload_fmt == IA_APPLICATION_JSON)
    {
        cJSON * root = cJSON_ParseWithLength(request->payload, request->payload_len);
        cJSON * j_val = cJSON_GetObjectItem(root, "value");
        if(!cJSON_IsNumber(j_val))
        {
            wa_monitor_set_decision(req_env, WA_Process_Drop);
            if(root) cJSON_Delete(root);
            return;
        } 
        value = j_val->valuedouble;
        if(root) cJSON_Delete(root);
    }
    else
    {
        wa_monitor_set_decision(req_env, WA_Process_Continue);
        return;
    }
    
    if(value > 10)
    {
        char buf[100];
        snprintf(buf, sizeof(buf),"%d", 10);
        int code = wa_monitor_get_decision_code(WA_Process_Modified);
        wa_set_response(req_env, code, TEXT_PLAIN, strlen(buf), buf);
        return;
    }
    else if(value < 1)
    {
        wa_monitor_set_decision(req_env, WA_Process_Drop);
    }
    else
    {
        wa_monitor_set_decision(req_env, WA_Process_Continue);
    }
}